/* eslint-disable */
import { Message } from '@arco-design/web-vue';
import { getItem } from '@/utils/storage';

// 将html标签过滤掉，并将&nbsp;&ensp;&emsp;&thinsp;等转化为标准的空格
export const filterHtmlTagsAndConvertToSpace = (html: string) => {
  // 创建临时div元素
  var div = document.createElement('div');
  // 将HTML字符串设置到div的innerHTML
  div.innerHTML = html;
  // 使用textContent获取去除所有HTML标签的纯文本
  var text = div.textContent || div.innerText || '';
  // 替换HTML空格实体为标准空格
  return text.replace(/&nbsp;|&ensp;|&emsp;|&thinsp;/gi, ' ');
};

// 字符串解析到html标签
const unescapeHtml = (html: string): string => {
  const map: { [key: string]: string } = {
    '&amp;': '&',
    '&lt;': '<',
    '&gt;': '>',
    '&quot;': '"',
    '&#039;': "'",
  };
  return html.replace(/&amp;|&lt;|&gt;|&quot;|&#039;/g, (m) => map[m]);
};

// 截取字符
export const truncateAndUnescape = (text: string, maxLength: any | undefined) => {
  if (maxLength === undefined || maxLength <= 0) return '';
  const unescapedText = unescapeHtml(text);
  return unescapedText.length > maxLength ? unescapedText.slice(0, maxLength) : unescapedText;
};

// 截取带标签的字符串
export const truncateHtml = (html: string, maxLength: number | undefined): string => {
  if (maxLength === undefined || maxLength <= 0) return '';

  const doc = new DOMParser().parseFromString(html, 'text/html');
  const text = doc.body.textContent || doc.body.innerText;

  if (text.length <= maxLength) {
    return html;
  }

  let truncatedText = text.slice(0, maxLength);
  let resultHtml = '';
  let charCount = 0;
  const openTags: string[] = [];

  const traverse = (node: Node) => {
    if (charCount >= maxLength) return;

    if (node.nodeType === Node.TEXT_NODE) {
      const remaining = maxLength - charCount;
      resultHtml += node.textContent!.slice(0, remaining);
      charCount += node.textContent!.length;
    } else if (node.nodeType === Node.ELEMENT_NODE) {
      const element = node as HTMLElement;
      openTags.push(element.tagName.toLowerCase());
      resultHtml += `<${element.tagName.toLowerCase()}${Array.from(element.attributes)
        .map((attr) => ` ${attr.name}="${attr.value}"`)
        .join('')}>`;

      for (let i = 0; i < element.childNodes.length; i++) {
        traverse(element.childNodes[i]);
        if (charCount >= maxLength) break;
      }

      if (charCount < maxLength) {
        resultHtml += `</${element.tagName.toLowerCase()}>`;
        openTags.pop();
      }
    }
  };

  traverse(doc.body);

  while (openTags.length > 0) {
    const tag = openTags.pop()!;
    resultHtml += `</${tag}>`;
  }
  // 移除最外围的body标签
  const temporaryDoc = new DOMParser().parseFromString(resultHtml, 'text/html');
  return temporaryDoc.body.innerHTML;
};

// 截取200字，保留a标签，最后将a标签截取完整
export const truncateHtmlWithLinks = (html: string, limit: number | undefined): string => {
  const div = document.createElement('div');
  div.innerHTML = html;

  let result = '';
  let count = 0;

  function traverse(node) {
    if (limit !== undefined && count >= limit && !(node.nodeName.toLowerCase() === 'a' && result.endsWith('</a>'))) {
      return;
    }

    if (node.nodeType === Node.TEXT_NODE) {
      let text = node.nodeValue;
      let remaining = limit ? limit - count : undefined;
      let match = text.match(new RegExp(`^.{0,${remaining}}`));
      if (match) {
        result += match[0];
        count += match[0].length;
      }
    } else if (node.nodeType === Node.ELEMENT_NODE) {
      if (node.nodeName.toLowerCase() === 'p' && node.textContent?.trim() === '&nbsp;') {
      } else if (node.nodeName.toLowerCase() === 'a') {
        result += `<a${Array.from(node.attributes).map(attr => ` ${attr.name}="${attr.value}"`).join('')}>`;
        node.childNodes.forEach(traverse);
        result += '</a>';
      } else if (node.nodeName.toLowerCase() === 'div' && node.classList.contains('w-e-textarea-link-card-container')) {
        const title = node.getAttribute('data-title');
        const link = node.getAttribute('data-link');
        const target = `target="${node.getAttribute('data-w-e-type')}_${node.getAttribute('data-articleId')}"`;
        result += `<a class="w-e-textarea-link-card-text-content" href="${link}" ${target}>${title}</a>`;
      } else {
        node.childNodes.forEach(traverse);
      }
    }
  }

  div.childNodes.forEach(traverse);

  return result;
}
export const truncateHtmlWithLinksAndBr = (html: string, limit: number | undefined): string => {
  const div = document.createElement('div');
  div.innerHTML = html;

  let result = '';
  let count = 0;
  let openPTags = 0; // Track the number of unclosed <p> tags

  function traverse(node) {
    if (limit !== undefined && count >= limit && !(node.nodeName.toLowerCase() === 'a' && result.endsWith('</a>'))) {
      return;
    }

    if (node.nodeType === Node.TEXT_NODE) {
      let text = node.nodeValue || '';
      let remaining = limit ? limit - count : undefined;
      let match = remaining !== undefined ? text.match(new RegExp(`^.{0,${remaining}}`, 'u')) : [text];
      if (match) {
        result += match[0];
        count += match[0].length;
      }
    } else if (node.nodeType === Node.ELEMENT_NODE) {
      const nodeName = node.nodeName.toLowerCase();
      if (nodeName === 'p') {
        // Check if the <p> tag contains only whitespace or is empty.
        if (!node.textContent?.trim()) {
          return;
        }
        openPTags++;
        result += '<p>';
        node.childNodes.forEach(traverse);
        result += '</p>';
        openPTags--;
      } else if (nodeName === 'a') {
        result += `<a${Array.from(node.attributes).map(attr => ` ${attr.name}="${attr.value}"`).join('')}>`;
        node.childNodes.forEach(traverse);
        result += '</a>';
      } else if (nodeName === 'div' && node.classList.contains('w-e-textarea-link-card-container')) {
        const title = node.getAttribute('data-title') || '';
        const link = node.getAttribute('data-link') || '#';
        const target = `target="${node.getAttribute('data-w-e-type') || ''}_${node.getAttribute('data-articleId') || ''}"`;
        result += `<a class="w-e-textarea-link-card-text-content" href="${link}" ${target}>${title}</a>`;
      } else if (nodeName === 'br') {
        // Handle <br> tags specially to ensure line breaks are preserved.
        result += '<br>';
      } else {
        node.childNodes.forEach(traverse);
      }
    }
  }

  div.childNodes.forEach(traverse);

  // Close any remaining open <p> tags that weren't closed due to reaching the character limit.
  while (openPTags > 0) {
    result += '</p>';
    openPTags--;
  }

  return result;
}


export const truncateHtmlWithTags = (html: string, limit: number | undefined): string => {
  if (limit === undefined || limit <= 0) return '';

  const doc = new DOMParser().parseFromString(html, 'text/html');
  const text = doc.body.textContent || doc.body.innerText;

  if (text.length <= limit) {
    return html;
  }

  let resultHtml = '';
  let charCount = 0;
  const openTags: string[] = [];

  const traverse = (node: Node) => {
    if (charCount >= limit) return;

    if (node.nodeType === Node.TEXT_NODE) {
      const remaining = limit - charCount;
      resultHtml += node.textContent!.slice(0, remaining);
      charCount += node.textContent!.length;
    } else if (node.nodeType === Node.ELEMENT_NODE) {
      const element = node as HTMLElement;
      openTags.push(element.tagName.toLowerCase());
      resultHtml += `<${element.tagName.toLowerCase()}${Array.from(element.attributes)
        .map((attr) => ` ${attr.name}="${attr.value}"`)
        .join('')}>`;

      for (let i = 0; i < element.childNodes.length; i++) {
        traverse(element.childNodes[i]);
        if (charCount >= limit) break;
      }

      if (charCount < limit) {
        resultHtml += `</${element.tagName.toLowerCase()}>`;
        openTags.pop();
      }
    }
  };

  traverse(doc.body);

  while (openTags.length > 0) {
    const tag = openTags.pop()!;
    resultHtml += `</${tag}>`;
  }
  // 移除最外围的body标签
  const temporaryDoc = new DOMParser().parseFromString(resultHtml, 'text/html');
  return temporaryDoc.body.innerHTML;
}



// 过滤标签
export const filterHtmlTags = (input: string) => {
  return input
    .replace(/<br\s*\/?>/gi, '\n')
    .replace(/<\/?[^>]+(>|$)/g, '')
    .replace(/&nbsp;/g, '');
};

// 滤掉HTML标签中的<img>标签
export const filterImgTags = (html: string) => {
  var imgPattern = /<img[^>]*>/gi;
  var bgPattern = /background-image:[^;]+;/gi;

  // 过滤掉<img>标签
  var filteredHtml = html.replace(imgPattern, '');

  // 过滤掉CSS样式中的background-image属性
  filteredHtml = filteredHtml.replace(bgPattern, '');

  return filteredHtml;
};

// 将字符串中的<和>符号替换为HTML实体，以便在浏览器中正确显示。
export function replaceSymbols(str: string) {
  return str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

// 检查文件是否符合上传条件
import { getFileExtension } from '@/utils/fileExtensions';
export function beforeUploadEvent(file: any) {
  const isSupportedType = ['docx'].includes(getFileExtension(file.name).toLowerCase());
  const isUnderSizeLimit = file.size / 1024 / 1024 <= 10;

  if (!isSupportedType) {
    Message.error('仅支持 docx 格式的文档');
  } else if (!isUnderSizeLimit) {
    Message.warning('文档大小不能超过 10MB');
  }

  return isSupportedType && isUnderSizeLimit;
}

// 检测敏感词
// 检测是否有本地敏感词
let detectedSensitiveWords: string[] = [];
export const checkSensitiveWords = async (content) => {
  detectedSensitiveWords = [];
  const sensitiveWords = (await getItem('sensitiveWords')) || [];
  const sensitiveWordSet = new Set(sensitiveWords);

  // 检查内容中是否包含敏感词
  sensitiveWordSet.forEach((word) => {
    if (content.includes(word)) {
      detectedSensitiveWords.push(word);
    }
  });
  return detectedSensitiveWords;
};


export function isContentOnlyWhitespace(htmlContent: string): boolean {
  console.log('htmlContent', htmlContent);
  // 尝试使用 DOMParser 解析 HTML
  const parser = new DOMParser();
  try {
    const doc = parser.parseFromString(htmlContent, 'text/html');
    const paragraphs:any = doc.body.querySelectorAll('p');
    for (let i = 0; i < paragraphs.length; i++) {
      const paragraph = paragraphs[i];
      // 检查每个 <p> 标签内的文本节点是否全为空白
      if (paragraph.textContent.trim().length > 0) {
        // 如果找到非空白文本，则内容不为空
        return false;
      }
    }
    return true; // 所有 <p> 标签内的文本节点均为空白
  } catch (error) {
    // 如果解析失败（例如，HTML 不合法），则认为内容无效
    return true;
  }
}

// 将所有a链接中带有 data-w-e-type="mention" 只保留span标签和文本，其他属性全部过滤掉
export const filterMention = (htmlContent: string): string => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(htmlContent, 'text/html');
  
  // 选择所有带有 data-w-e-type="mention" 属性的 a 链接
  const links = doc.body.querySelectorAll('a[data-w-e-type="mention"]');
  
  // 遍历每个链接
  links.forEach((link) => {
    const span = document.createElement('span');
    span.textContent = link.textContent.trim(); // 将链接文本复制到新的 span 元素中
    if(link.parentNode){
      link.parentNode.replaceChild(span, link); // 替换原始链接元素
    }    
  });
  // 将span前后的空格过滤掉
  // 将修改后的文档转换回字符串形式
  return doc.body.innerHTML.trim();
}